<template>
  <div>
    <el-card shadow="never">
      <el-skeleton :loading="loading" animated>
        <el-row :gutter="16" justify="space-between">
          <el-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
            <div class="flex items-center">
              <el-avatar :src="avatar" :size="70" class="mr-16px">
                <img src="@/assets/imgs/avatar.gif" alt="" />
              </el-avatar>
              <div>
                <div class="text-20px">
                  {{ t('workplace.welcome') }} {{ username }} {{ t('workplace.happyDay') }}
                </div>
                <!-- <div class="mt-10px text-14px text-gray-500">
                  {{ t('workplace.toady') }}，20℃ - 32℃！
                </div> -->
              </div>
            </div>
          </el-col>
        </el-row>
      </el-skeleton>
    </el-card>
  </div>

  <!-- <el-row :gutter="8" class="mt-8px">
    <el-col :span="6"> -->
      <!-- 员工概况 -->
      <!-- <StaffOverview title="员工概况" :staffData="projects" :loading="loading" /> -->
    <!-- 员工概况 -->
     <!-- 员工概况 -->
     <!-- <PersonnelOverview title="员工概况" unit="人" :personnelData="personnelData1" :loading="loading" />
    </el-col>
    <el-col :span="6"> -->
      <!-- 员工合同 -->
      <!-- <PersonnelOverview title="员工合同" unit="份" :personnelData="personnelData2" :loading="loading" />
    </el-col>
    <el-col :span="6"> -->
      <!-- 主任务 -->
      <!-- <PersonnelOverview title="主任务" unit="个" :personnelData="personnelData3" :loading="loading" />
    </el-col>
    <el-col :span="6"> -->
      <!-- 子任务 -->
      <!-- <PersonnelOverview title="子任务" unit="个" :personnelData="personnelData4" :loading="loading" />
    </el-col>
  </el-row> -->

  <div  class="mt-8px">
    <!-- 快捷入口 -->
    <el-card shadow="never">
        <template #header>
          <div class="h-3 flex justify-between">
            <span>快捷入口</span>
          </div>
        </template>
        <el-skeleton :loading="loading" animated>
          <el-row :gutter="20">
            <el-col
v-for="(item, index) in shortcut" :key="`shortcut-${index}`" :span="4" class="shortcut-item">
              <div class="shortcut-content">
                <div class="shortcut-icon" :style="{ backgroundColor: item.color }">
                  <Icon :icon="item.icon" :size="30" />
                </div>
                <div class="shortcut-text">
                  <el-link type="default" :underline="false" @click="handleShortcutClick(item.url)">
                    {{ item.name }}
                  </el-link>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-skeleton>
      </el-card>
  </div>

  <div class="mt-8px">
      <el-row :gutter="8">
        <el-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
          <el-card shadow="never" class="mt-8px">
            <template #header>
              <div class="h-3 flex justify-between">
                <span>加班申请</span>
              </div>
            </template>
            <el-skeleton :loading="loading" animated>
              <Echart :options="overtimeBarOptions" :height="300" />
            </el-skeleton>
          </el-card>
        </el-col>
        <el-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
          <el-card shadow="never" class="mt-8px">
            <template #header>
              <div class="h-3 flex justify-between">
                <span>请假申请</span>
              </div>
            </template>
            <el-skeleton :loading="loading" animated>
              <Echart :options="leaveBarOptions" :height="300" />
            </el-skeleton>
          </el-card>
        </el-col>
      </el-row>
      <!-- 各类型审批数量柱状图 -->
      <el-row :gutter="8">
        <el-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
          <el-card shadow="never" class="mt-8px">
            <template #header>
              <div class="h-3 flex justify-between">
                <span>出差申请</span>
              </div>
            </template>
            <el-skeleton :loading="loading" animated>
              <Echart :options="businessTripBarOptions" :height="300" />
            </el-skeleton>
          </el-card>
        </el-col>
        <el-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
          <el-card shadow="never" class="mt-8px">
            <template #header>
              <div class="h-3 flex justify-between">
                <span>补卡申请</span>
              </div>
            </template>
            <el-skeleton :loading="loading" animated>
              <Echart :options="reissueCardBarOptions" :height="300" />
            </el-skeleton>
          </el-card>
        </el-col>
      </el-row>
  </div>

  <!-- 审批弹框 -->
  <ApprovalDialog v-model="approvalDialogVisible" />
</template>
<script lang="ts" setup>
import { set } from 'lodash-es'
import { EChartsOption } from 'echarts'
import { formatTime } from '@/utils'

import { useUserStore } from '@/store/modules/user'
import type { WorkplaceTotal, Project, Notice, Shortcut } from './types'
import { pieOptions, barOptions } from './echarts-data'
import { useRouter } from 'vue-router'
import { User, Briefcase, Document, Clock } from '@element-plus/icons-vue'
import { OvertimeApplyApi } from '@/api/oa/overtimeapply'
import { LeaveApplyApi } from '@/api/oa/leaveapply'
import { BusinessTripApplyApi } from '@/api/oa/businesstripapply'
import { ReissueCardApplyApi } from '@/api/oa/reissuecardapply'
defineOptions({ name: 'Index' })

const { t } = useI18n()
const router = useRouter()
const userStore = useUserStore()
// const { setWatermark } = useWatermark()
const loading = ref(true)
const avatar = userStore.getUser.avatar
const username = userStore.getUser.nickname
const pieOptionsData = reactive<EChartsOption>(pieOptions) as EChartsOption
// 获取统计数
let totalSate = reactive<WorkplaceTotal>({
  project: 0,
  access: 0,
  todo: 0
})

const getCount = async () => {
  const data = {
    project: 40,
    access: 2340,
    todo: 10
  }
  totalSate = Object.assign(totalSate, data)
}

// 获取项目数
let projects = reactive<Project[]>([])
const getProject = async () => {
  const data = [
    {
      value: 10000,
      icon: User,
      message: '在职员工',
      color: '#409EFF'
    },
    {
      value: 200,
      icon: Briefcase,
      message: '员工合同',
      color: 'rgb(148.6, 212.3, 117.1)'
    },
    // {
    //   value: 8000,
    //   icon: Document,
    //   message: '正式员工',
    //   color: 'rgb(248, 152.1, 152.1)'
    // },
    {
      value: 1800,
      icon: Clock,
      message: '离职档案',
      color: '#909399'
    },
  ]
  projects = Object.assign(projects, data)
}
// 人事
const personnelData1 = reactive([
  { count: 120, status: '在职员工' },
  { count: 30, status: '离职档案' },
  { count: 80, status: '员工合同' }
])
const personnelData2 = reactive([
  { count: 120, status: '全职' },
  { count: 30, status: '兼职' },
  { count: 80, status: '临时' }
])
const personnelData3 = reactive([
  { count: 120, status: '进行中' },
  { count: 30, status: '已完成' },
  { count: 80, status: '我发起的' }
])
const personnelData4 = reactive([
{ count: 120, status: '进行中' },
  { count: 30, status: '已完成' },
  { count: 80, status: '我执行的' }
])
// 审批概况
const approvalData = reactive([
  { count: 120, description: '全部' },
  { count: 45, description: '审批中' },
  { count: 30, description: '已完成' },
  { count: 15, description: '已撤回' }
])
const approvalBarOptions = reactive<EChartsOption>({
  title: {
    text: '',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  xAxis: {
    type: 'category',
    data: approvalData.map((item) => item.description),
    axisLabel: {
      rotate: 45
    }
  },
  yAxis: {
    type: 'value',
    name: '单位（人）'
  },
  series: [
    {
      name: '审批数量',
      type: 'bar',
      data: approvalData.map((item) => item.count),
      barWidth: '50%',
      itemStyle: {
        color: '#409EFF'
      }
    }
  ]
});
// 获取通知公告
let notice = reactive<Notice[]>([])
const getNotice = async () => {
  const data = [
    {
      title: '系统支持 JDK 8/17/21，Vue 2/3',
      type: '技术兼容性',
      keys: ['JDK', 'Vue'],
      date: new Date()
    },
    {
      title: '后端提供 Spring Boot 2.7/3.2 + Cloud 双架构',
      type: '架构灵活性',
      keys: ['Boot', 'Cloud'],
      date: new Date()
    },
    {
      title: '全部开源，个人与企业可 100% 直接使用，无需授权',
      type: '开源免授权',
      keys: ['无需授权'],
      date: new Date()
    },
    {
      title: '国内使用最广泛的快速开发平台，远超 10w+ 企业使用',
      type: '广泛企业认可',
      keys: ['最广泛', '10w+'],
      date: new Date()
    }
  ]
  notice = Object.assign(notice, data)
}

// 获取快捷入口
let shortcut = reactive<Shortcut[]>([])

const getShortcut = async () => {
  const data = [
    {
      name: '绩效',
      icon: 'ep:avatar',
      url: '/work/my-employee-score',
      color: '#1fdaca'
    },
    {
      name: '考勤',
      icon: 'ep:brush-filled',
      url: '/work/attendance/attendance-owner',
      color: '#ff6b6b'
    },
    {
      name: '审批',
      icon: 'fa:tasks',
      url: 'approvalProcess',
      color: '#7c3aed'
    },
    {
      name: '日程安排',
      icon: 'simple-icons:erpnext',
      url: '/work/schedule-arrangement',
      color: '#3fb27f'
    },
    {
      name: '客户',
      icon: 'ep:avatar',
      url: '/crm/customer',
      color: '#4daf1bc9'
    },
    {
      name: '公告',
      icon: 'ep:chat-dot-round',
      url: '/work/receiverNotice',
      color: '#1a73e8'
    }
  ]
  shortcut = Object.assign(shortcut, data)
}
const moreApproval = () => {
  router.push('/bpm/task/todo')
}
// 用户来源
const getUserAccessSource = async () => {
  const data = [
    { value: 335, name: 'analysis.directAccess' },
    { value: 310, name: 'analysis.mailMarketing' },
    { value: 234, name: 'analysis.allianceAdvertising' },
    { value: 135, name: 'analysis.videoAdvertising' },
    { value: 1548, name: 'analysis.searchEngines' }
  ]
  set(
    pieOptionsData,
    'legend.data',
    data.map((v) => t(v.name))
  )
  pieOptionsData!.series![0].data = data.map((v) => {
    return {
      name: t(v.name),
      value: v.value
    }
  })
}
const barOptionsData = reactive<EChartsOption>(barOptions) as EChartsOption
// 控制弹框显示
const approvalDialogVisible = ref(false)


// 周活跃量
const getWeeklyUserActivity = async () => {
  const data = [
    { value: 13253, name: 'analysis.monday' },
    { value: 34235, name: 'analysis.tuesday' },
    { value: 26321, name: 'analysis.wednesday' },
    { value: 12340, name: 'analysis.thursday' },
    { value: 24643, name: 'analysis.friday' },
    { value: 1322, name: 'analysis.saturday' },
    { value: 1324, name: 'analysis.sunday' }
  ]
  set(
    barOptionsData,
    'xAxis.data',
    data.map((v) => t(v.name))
  )
  set(barOptionsData, 'series', [
    {
      name: t('analysis.activeQuantity'),
      data: data.map((v) => v.value),
      type: 'bar'
    }
  ])
}

// 加班申请月度统计
const overtimeBarOptions = reactive({
  title: {
    text: '本年度加班申请统计',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: 50,
    right: 20,
    bottom: 20
  },
  xAxis: {
    type: 'category',
    data: [],
    axisTick: {
      alignWithLabel: true
    }
  },
  yAxis: {
    type: 'value',
    name: '申请次数'
  },
  series: [
    {
      name: '加班申请数',
      type: 'bar',
      data: [],
      barWidth: '50%',
      itemStyle: {
        color: '#409EFF'
      }
    }
  ]
} as EChartsOption)

const fetchOvertimeStatistics = async () => {
  const userId = userStore.getUser.id
  const year = new Date().getFullYear()
  try {
    const res = await OvertimeApplyApi.getMonthlyApprovedCountByUser(userId, year)
    // 构造12个月的完整数据
    const monthMap = new Map<number, number>()
    if (res && Array.isArray(res)) {
      res.forEach((item: { month: number; count: number }) => {
        monthMap.set(item.month, item.count)
      })
    }
    overtimeBarOptions.xAxis.data = Array.from({ length: 12 }, (_, i) => `${i + 1}月`)
    overtimeBarOptions.series[0].data = Array.from({ length: 12 }, (_, i) => monthMap.get(i + 1) || 0)
  } catch (e) {
    overtimeBarOptions.xAxis.data = Array.from({ length: 12 }, (_, i) => `${i + 1}月`)
    overtimeBarOptions.series[0].data = Array(12).fill(0)
  }
}

// 请假申请月度统计
const leaveBarOptions = reactive({
  title: {
    text: '本年度请假申请统计',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: 50,
    right: 20,
    bottom: 20
  },
  xAxis: {
    type: 'category',
    data: [],
    axisTick: {
      alignWithLabel: true
    }
  },
  yAxis: {
    type: 'value',
    name: '申请次数'
  },
  series: [
    {
      name: '请假申请数',
      type: 'bar',
      data: [],
      barWidth: '50%',
      itemStyle: {
        color: '#67C23A'
      }
    }
  ]
} as EChartsOption)

const fetchLeaveStatistics = async () => {
  const userId = userStore.getUser.id
  const year = new Date().getFullYear()
  try {
    const res = await LeaveApplyApi.getMonthlyApprovedCountByUser(userId, year)
    const monthMap = new Map<number, number>()
    if (res && Array.isArray(res)) {
      res.forEach((item: { month: number; count: number }) => {
        monthMap.set(item.month, item.count)
      })
    }
    leaveBarOptions.xAxis.data = Array.from({ length: 12 }, (_, i) => `${i + 1}月`)
    leaveBarOptions.series[0].data = Array.from({ length: 12 }, (_, i) => monthMap.get(i + 1) || 0)
  } catch (e) {
    leaveBarOptions.xAxis.data = Array.from({ length: 12 }, (_, i) => `${i + 1}月`)
    leaveBarOptions.series[0].data = Array(12).fill(0)
  }
}

// 出差申请月度统计
const businessTripBarOptions = reactive({
  title: {
    text: '本年度出差申请统计',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: 50,
    right: 20,
    bottom: 20
  },
  xAxis: {
    type: 'category',
    data: [],
    axisTick: {
      alignWithLabel: true
    }
  },
  yAxis: {
    type: 'value',
    name: '申请次数'
  },
  series: [
    {
      name: '出差申请数',
      type: 'bar',
      data: [],
      barWidth: '50%',
      itemStyle: {
        color: '#E6A23C'
      }
    }
  ]
} as EChartsOption)

const fetchBusinessTripStatistics = async () => {
  const userId = userStore.getUser.id
  const year = new Date().getFullYear()
  try {
    const res = await BusinessTripApplyApi.getMonthlyApprovedCountByUser(userId, year)
    const monthMap = new Map<number, number>()
    if (res && Array.isArray(res)) {
      res.forEach((item: { month: number; count: number }) => {
        monthMap.set(item.month, item.count)
      })
    }
    businessTripBarOptions.xAxis.data = Array.from({ length: 12 }, (_, i) => `${i + 1}月`)
    businessTripBarOptions.series[0].data = Array.from({ length: 12 }, (_, i) => monthMap.get(i + 1) || 0)
  } catch (e) {
    businessTripBarOptions.xAxis.data = Array.from({ length: 12 }, (_, i) => `${i + 1}月`)
    businessTripBarOptions.series[0].data = Array(12).fill(0)
  }
}

// 补卡申请月度统计
const reissueCardBarOptions = reactive({
  title: {
    text: '本年度补卡申请统计',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: 50,
    right: 20,
    bottom: 20
  },
  xAxis: {
    type: 'category',
    data: [],
    axisTick: {
      alignWithLabel: true
    }
  },
  yAxis: {
    type: 'value',
    name: '申请次数'
  },
  series: [
    {
      name: '补卡申请数',
      type: 'bar',
      data: [],
      barWidth: '50%',
      itemStyle: {
        color: '#F56C6C'
      }
    }
  ]
} as EChartsOption)

const fetchReissueCardStatistics = async () => {
  const userId = userStore.getUser.id
  const year = new Date().getFullYear()
  try {
    const res = await ReissueCardApplyApi.getMonthlyApprovedCountByUser(userId, year)
    const monthMap = new Map<number, number>()
    if (res && Array.isArray(res)) {
      res.forEach((item: { month: number; count: number }) => {
        monthMap.set(item.month, item.count)
      })
    }
    reissueCardBarOptions.xAxis.data = Array.from({ length: 12 }, (_, i) => `${i + 1}月`)
    reissueCardBarOptions.series[0].data = Array.from({ length: 12 }, (_, i) => monthMap.get(i + 1) || 0)
  } catch (e) {
    reissueCardBarOptions.xAxis.data = Array.from({ length: 12 }, (_, i) => `${i + 1}月`)
    reissueCardBarOptions.series[0].data = Array(12).fill(0)
  }
}

const getAllApi = async () => {
  await Promise.all([
    getCount(),
    getProject(),
    getNotice(),
    getShortcut(),
    getUserAccessSource(),
    getWeeklyUserActivity(),
    fetchOvertimeStatistics(),
    fetchLeaveStatistics(),
    fetchBusinessTripStatistics(),
    fetchReissueCardStatistics()
  ])
  loading.value = false
}

const handleProjectClick = (message: string) => {
  window.open(`https://${message}`, '_blank')
}

const handleShortcutClick = (url: string) => {
  if (url === 'approvalProcess') {
    approvalDialogVisible.value = true
  } else {
    router.push(url)
  }
}

getAllApi()
</script>
<style scoped>
.shortcut-item {
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.shortcut-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 16px 0;
  transition: all 0.3s;
}

/* .shortcut-content:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-4px);
} */

.shortcut-icon {
  width: 50px;
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 10px;
  margin-bottom: 8px;
  color: #fff;
  /* 确保图标颜色为白色，与背景色形成对比 */
}

.shortcut-text {
  font-size: 14px;
  color: #333;
}

.personnel-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 16px;
  text-align: center;
  background-color: #fff;
  transition: all 0.3s;
}

.personnel-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-4px);
}

.personnel-count {
  font-size: 16px;
  color: #333;
  margin-bottom: 8px;

}

.personnel-count strong {
  font-weight: bold;
  font-size: 20px;
}

.personnel-status {
  font-size: 14px;
  color: #666;
}

.approval-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 16px;
  text-align: center;
  background-color: #fff;
  /* border: 1px solid #f0f0f0; */
  border-radius: 8px;
  transition: all 0.3s;

}

/* .approval-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-4px);
} */

.approval-count {
  font-size: 20px;
  color: #333;
  margin-bottom: 8px;
  font-weight: bold;
}

.approval-description {
  font-size: 14px;
  color: #666;
}
</style>